package com.cms.controller.front;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.cms.Feedback;
import com.cms.entity.*;
import com.cms.interceptor.SiteInterceptor;
import com.cms.routes.RouteMapping;
import com.jfinal.aop.Before;

/**
 * Controller - api
 * 
 * 
 * 
 */
@RouteMapping(url = "/api")
@Before(SiteInterceptor.class)
public class ApiController extends BaseController {

    /**
     * 点击数
     */
    public void updateContentHits() {
        Long id = getParaToLong(0);
        if (id == null) {
            renderJson(0L);
            return;
        }
        Content content = new Content().dao().findById(id);
        Long hits = content.getHits();
        hits = hits+1;
        content.setHits(hits);
        content.update();
        renderJavascript("document.write("+hits+")");
    }

    /**
     * 点击数
     */
    public void updatePushContentHits() {
        Long id = getParaToLong(0);
        if (id == null) {
            renderJson(0L);
            return;
        }
        PushContent content = new PushContent().dao().findById(id);
        Long hits = content.getHits();
        hits = hits+1;
        content.setHits(hits);
        content.update();
        renderJavascript("document.write("+hits+")");
    }
    
    /**
     * 保存
     */
    public void saveForm(){
        Long modelId = getParaToLong("modelId");
        Long contentId = getParaToLong("contentId");
        Model model = new Model().dao().findById(modelId);
        if(model.getIsCaptcha()){
            if(!validateCaptcha("captcha")){
                renderJson(Feedback.error("验证码错误!"));
                return;
            }
        }
        List<ModelField> modelFields = new ModelField().dao().findList(modelId,true,getCurrentSite().getRealId());
        Map<String,Object> map = new HashMap<String,Object>();
        for(ModelField modelField : modelFields){
            String value = getPara(modelField.getName());
            map.put(modelField.getName(), value);
        }
        Form form = new Form();
        form.setSiteId(getCurrentSite().getRealId());
        form.setCreateDate(new Date());
        form.setModifyDate(new Date());
        form.setModelId(modelId);
        form.setContentId(contentId);
        form.setModelFieldValue(JSONObject.toJSONString(map));
        form.setIsEnabled(false);
        form.save();
        renderJson(Feedback.success(new HashMap<>()));
    }
}
